<?php


namespace app\wechat\controller;


use app\BaseController;
use app\service\model\MemberModel;
use app\service\Y;
use EasyWeChat\Factory;

class Notify extends BaseController
{

    /**
     * 微信消息推送
     * @return string
     */
    public function index(): string
    {
        try {
            $app = Factory::officialAccount(config('wechat.official_account'));

            $app->server->push(function ($message) use ($app) {
                switch ($message['MsgType']) {
                    case 'event':
                        if ($message['Event'] == 'subscribe') {
                            $wx_info = $app->user->get($message['FromUserName']);
                            file_put_contents(runtime_path() . 'wx_node.log', date("Y-m-d H:i:s")."//". json_encode($wx_info) ."\n", FILE_APPEND);
                            $member = MemberModel::where('wx_unionid', '=', $wx_info['unionid'])->find();
                            if ($member) {
                                $member->gzh_openid = $message['FromUserName'];
                                $member->subscribe = 1;
                                $member->save();
                            } else {
                                MemberModel::create([
                                    'wx_unionid' => $res['unionid'] ?? '',
                                    'gzh_openid' => $message['FromUserName'],
                                    'nickname' => $wx_info['nickname'],
                                    'headimgurl' => $wx_info['headimgurl'],
                                    'subscribe' => 1
                                ]);
                            }

                            return '遇见甜蜜！！';
                        } else if ($message['Event'] == 'unsubscribe') {
                            $member = MemberModel::where('gzh_openid', '=', $message['FromUserName'])->find();
                            if ($member) {
                                $member->subscribe = 0;
                                $member->save();
                            }
                        }
                        break;
                    default:
                        return '';
                        break;
                }

            });

            $app->server->serve()->send();
//            return '什么鬼';
        } catch (\Exception $e) {
            trace($e->getMessage());
            return $e->getMessage();
        }
    }
}